﻿using NetCore8Demo.Models.PLC;
using System.Text.RegularExpressions;
using TextBox = System.Windows.Forms.TextBox;
using Timer = System.Windows.Forms.Timer;
using ToolTip = System.Windows.Forms.ToolTip;
namespace NetCore8Demo.Views.PLC
{
    public partial class ShowDynPlcAddressForm : Form
    {
        public ShowDynPlcAddressForm(List<PlcAddressInfo> plcAddressInfoList, List<string>? titleInfoList)
        {
            InitializeComponent();
            //if (titleInfoList != null && titleInfoList.Count > 0)
            if (titleInfoList is { Count: > 0 })
            {
                _titleInfoList = titleInfoList;
            }
            Init();
            _plcAddressInfoList = plcAddressInfoList;
        }

        public ShowDynPlcAddressForm()
        {
            InitializeComponent();
            Init();
        }

        

        List<PlcAddressInfo> _plcAddressInfoList = new ();
        List<string> _titleInfoList = ["PLC信息"];

        private TableLayoutPanel _titleTableLayoutPanel = new ();
        private int _currentTitleIndex;

        private TableLayoutPanel _mainTableLayoutPanel = new();
        private int _panelWidth = 700;
        private int _panelHeight = 800;
        private int _panelRowCount = 19;//设置行数
        private int _panelColumnCount = 7;//设置列数

        private ToolTip _toolTip = new();
        private Timer _timer = new();

        private void ShowDynPlcForm_Load(object sender, EventArgs e)
        {

        }

        #region 初始化绘制页面
        public void Init()
        {
            this.Height = _panelHeight + 60;
            this.Width = _panelWidth + 30;
            //this.MaximizeBox = false;
            //this.MinimizeBox = false;
            this.StartPosition = FormStartPosition.CenterParent;

            //显示网格线
            //_mainTableLayoutPanel.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
            InitTabLayOutPanel();

            //还可以解决最大最小化时卡的问题
            components = new System.ComponentModel.Container();
            _toolTip = new ToolTip(this.components);

            AddTabLayOutPanelControl();

            // 初始化 Timer
            this._timer.Interval = 100;  
            this._timer.Tick += Timer_Tick;
            this._timer.Start();  

        }

        public void InitTabLayOutPanel()
        {
            _mainTableLayoutPanel.Location = new Point(5, 5);
            _mainTableLayoutPanel.RowCount = _panelRowCount;
            _mainTableLayoutPanel.ColumnCount = _panelColumnCount;

            _mainTableLayoutPanel.Dock = DockStyle.Fill;
            _mainTableLayoutPanel.BackColor = Color.Silver;

            //列宽
            _mainTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 45));
            _mainTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20));
            _mainTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30));
            _mainTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 10));
            _mainTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20));
            _mainTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30));
            _mainTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 45));

            //行高
            _mainTableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 45));
            _mainTableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));
            for (int i = 0; i < 16; i++)
            {
                _mainTableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, (float)6.25));
            }
            _mainTableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));

            this.Controls.Add(_mainTableLayoutPanel);
        }

        public void AddTabLayOutPanelControl()
        {
            for (int i = 0; i < _panelRowCount; i++)
            {
                if (i == 0)
                {
                    _titleTableLayoutPanel.RowCount = 1;
                    _titleTableLayoutPanel.ColumnCount = _titleInfoList.Count;
                    _titleTableLayoutPanel.Dock = DockStyle.Fill;
                    

                    for (int j = 0; j < _titleInfoList.Count; j++)
                    {
                        Label label = GetTitleLabel(j);
                        
                        _titleTableLayoutPanel.Controls.Add(label,j,0);
                        _titleTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
                    }

                    
                    _mainTableLayoutPanel.SetColumnSpan(_titleTableLayoutPanel, 7);
                    _mainTableLayoutPanel.Controls.Add(_titleTableLayoutPanel, 0, 0);
                    continue;
                }
                if (i == 1 || i == _panelRowCount - 1)
                {
                    continue;
                }

                _mainTableLayoutPanel.Controls.Add(GetNameLabel(1, i), 1, i);
                _mainTableLayoutPanel.Controls.Add(GetValueTextBox(2, i), 2, i);

                _mainTableLayoutPanel.Controls.Add(GetNameLabel(4, i), 4, i);
                _mainTableLayoutPanel.Controls.Add(GetValueTextBox(5, i), 5, i);
            }

        }


        /// <summary>
        /// 需要在控件已经添加到页面后调用
        /// 不然如果设置了Dock属性，获取的数据不对
        /// </summary>
        /// <param name="column"></param>
        /// <returns></returns>
        public int GetColumnWidth(int column)
        {

            if (column > _mainTableLayoutPanel.ColumnCount) return 0;
            ColumnStyle columnStyle = _mainTableLayoutPanel.ColumnStyles[column];
            if (columnStyle.SizeType == SizeType.Percent)
            {
                float columnWidthPercentage = columnStyle.Width;
                return (int)(this._mainTableLayoutPanel.ClientSize.Width * (columnWidthPercentage / 100.0f));
            }
            else
            {
                return (int)columnStyle.Width;
            }

        }

        /// <summary>
        /// 需要在控件已经添加到页面后调用
        /// 不然如果设置了Dock属性，获取的数据不对
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public int GetRowHeight(int row)
        {
            if (row > _mainTableLayoutPanel.RowCount) return 0;
            RowStyle rowStyle = _mainTableLayoutPanel.RowStyles[row];
            if (rowStyle.SizeType == SizeType.Percent)
            {
                float columnWidthPercentage = rowStyle.Height;
                return (int)(this._mainTableLayoutPanel.ClientSize.Width * (columnWidthPercentage / 100.0f));
            }
            else
            {
                return (int)rowStyle.Height;
            }

        }


        #endregion

        #region 生成页面不同控件

        public Label GetTitleLabel(int titleIndex)
        {

            Label label = new Label();
            label.Name = "TitleLabel"+ titleIndex;
            label.Text = _titleInfoList[titleIndex];
            label.AutoSize = true;
            label.Dock = DockStyle.Fill;
            label.BackColor = titleIndex == 0 ? Color.DarkCyan : Color.Transparent;
           
            label.Font = new Font(label.Font.FontFamily, 16, label.Font.Style);
            label.TextAlign = ContentAlignment.MiddleCenter;
            label.Click += Title_Tick;
            return label;
        }

        public Label GetNameLabel(int column, int row)
        {
            Label label = new Label();
            label.Name = "NameLabel" + GetIdByColAndRow(column, row);
            label.Text = "备用:";
            label.Font = new Font(label.Font.FontFamily, 12, label.Font.Style);
            label.TextAlign = ContentAlignment.MiddleRight;
            label.AutoSize = true;
            label.Dock = DockStyle.Fill;
            //label.Anchor = AnchorStyles.Right;

           // label.Size = new Size(GetColumnWidth(column), GetRowHeight(row));


            return label;
        }

        public Label GetValueLabel(int column, int row)
        {

            Label label = new Label();
            label.Font = new Font(label.Font.FontFamily, 12, label.Font.Style);
            label.Name = "ValueLabel" + GetIdByColAndRow(column, row);
            label.Text = "";
            label.AutoSize = true;
            label.Dock = DockStyle.Fill;
            label.TextAlign = ContentAlignment.MiddleLeft;
            return label;
        }

        public TextBox GetValueTextBox(int column, int row)
        {
            TextBox textBox = new TextBox();
            textBox.Name = "ValueLabel" + GetIdByColAndRow(column, row);
            textBox.Font = new Font(textBox.Font.FontFamily, 12, textBox.Font.Style);
            textBox.Text = "";
            textBox.ReadOnly = true;
            textBox.Anchor = AnchorStyles.Left;
            textBox.Size = new Size(GetColumnWidth(column), GetRowHeight(row));
            return textBox;
        }

        public int GetIdByColAndRow(int column, int row)
        {
            if (column < 3)
            {
                return row - 2;
            }
            return row + 14;
        }

        #endregion

        #region 页面方法

        private void Timer_Tick(object? sender, EventArgs e)
        {
            foreach (var item in _plcAddressInfoList)
            {
                int tempIndex = item.Index - (32 * _currentTitleIndex);
                if(tempIndex<0|| tempIndex>31) continue;
                var nameControl = this.Controls.Find("NameLabel" + tempIndex, true);
                if (nameControl.Length > 0 && nameControl[0] is Label)
                {
                    nameControl[0].Text = item.Name+":";
                }

                var valueControl = this.Controls.Find("ValueLabel" + tempIndex, true);
                if (valueControl.Length > 0 && (valueControl[0] is TextBox|| valueControl[0] is Label))
                {
                    valueControl[0].Text = item.Value;
                    if (item.Value.Length > 10)
                    {
                        _toolTip.SetToolTip(valueControl[0], item.Value);
                    }

                }
            }
        }

        private void Title_Tick(object? sender, EventArgs e)
        {
            if (_titleInfoList.Count <= 1)
            {
                return;
            }


            foreach (Control control in this._titleTableLayoutPanel.Controls)
            {
                if (control is Label label)
                {
                    label.BackColor = Color.Transparent;
                }
            }
           

            if (sender is Label currentLabel)
            {
                _currentTitleIndex = Convert.ToInt32(Regex.Replace(currentLabel.Name, @"\D", ""));

                currentLabel.BackColor = Color.DarkCyan;
            }


            for (int i = 0; i < 32; i++)
            {
                int tempIndex = i;
                var nameControl = this.Controls.Find("NameLabel" + tempIndex, true);
                if (nameControl.Length > 0 && nameControl[0] is Label)
                {
                    nameControl[0].Text ="备用:";
                }

                var valueControl = this.Controls.Find("ValueLabel" + tempIndex, true);
                if (valueControl.Length > 0 && (valueControl[0] is TextBox || valueControl[0] is Label))
                {
                    valueControl[0].Text = "";
                }
            }
           

        }

        #endregion


    }
}
